#include "defs.h"
#include <time.h>
#include <stdio.h>
#include <string.h>
#include "thread_join_win32.h"

CThreadJoinWin32::CThreadJoinWin32()
{}

CThreadJoinWin32::~CThreadJoinWin32()
{}

DWORD CThreadJoinWin32::FileThreadFunc(LPVOID lpParameters)
{
    time_t now = time(NULL);
    struct tm* t = localtime(&now);
    char timeStr[32] = { 0 };
    sprintf_s(timeStr, 32, "%04d/%02d/%02d %02d:%02d:%02d",
              t->tm_year + 1900,
              t->tm_mon + 1,
              t->tm_mday,
              t->tm_hour,
              t->tm_min,
              t->tm_sec);
    FILE* fp = fopen(TIME_FILENAME, "w");
    if (fp == NULL) {
        printf("failed to create time.txt\n");
        return 1;
    }

    size_t sizeToWrite = strlen(timeStr) + 1;
    size_t ret = fwrite(timeStr, 1, sizeToWrite, fp);
    if (ret != sizeToWrite) {
        printf("write file error\n");
    }

    fclose(fp);

    return 2;
}


int CThreadJoinWin32::start()
{
    DWORD dwFileThreadId;
    HANDLE hFileThread = CreateThread(NULL, 0, FileThreadFunc, NULL, 0, &dwFileThreadId);
    if (hFileThread == NULL) {
        printf("failed to create file thread\n");
        return -1;
    }

    WaitForSingleObject(hFileThread, INFINITE);

    FILE* fp = fopen(TIME_FILENAME, "r");
    if (fp == NULL) {
        printf("open file error\n");
        return -2;
    }

    char buf[32] = { 0 };
    size_t sizeRead = fread(buf, 1, 32, fp);
    if (sizeRead == 0) {
        printf("read file error\n");
        fclose(fp);
        return -1;
    }

    printf("win32 current time is:%s\n", buf);
    fclose(fp);

    return 0;
}